# API视图
import logging
import json
from django.http import StreamingHttpResponse, JsonResponse
from django_redis import get_redis_connection
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from openai import APIError, APIConnectionError, RateLimitError, AuthenticationError
from .models import UserProfile
from .serializers import UserProfileSerializer
from .utils import extract_username, save_chat_history, generate_prompt
from .llm_client import LLMClient

# 配置日志
logger = logging.getLogger(__name__)


class UserProfileViewSet(viewsets.ModelViewSet):
    """用户资料视图集"""
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer

    @action(detail=False, methods=["post"])
    def recommend_outfit(self, request):
        """获取穿搭推荐"""
        try:
            query = request.data.get('query', '').strip()
            if not query:
                return Response(
                    {"error": "查询内容不能为空"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 提取用户名
            username = extract_username(query)
            if not username:
                return Response(
                    {"error": "无法从查询中提取用户名，请使用'为[用户名]推荐...'或'为[用户名]：[内容]'格式"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 查询用户信息
            try:
                user_profile = UserProfile.objects.get(username=username)
            except UserProfile.DoesNotExist:
                return Response(
                    {"error": f"用户'{username}'不存在，请先创建用户资料"},
                    status=status.HTTP_404_NOT_FOUND
                )

            # 获取历史对话
            redis_conn = get_redis_connection("default")
            history_key = f"user:chat:{username}"
            history = redis_conn.get(history_key)
            history_text = history.decode('utf-8') if history else ""

            # 智能处理查询内容
            processed_query = self._process_query(query, username)
            
            # 生成提示词
            prompt = generate_prompt(username, processed_query, history_text)

            # 创建LLM客户端
            llm_client = LLMClient()

            def stream_response():
                try:
                    # 调用LLM生成推荐，传递包含用户信息的prompt
                    for chunk in llm_client.stream_chat(prompt):
                        yield f"data: {json.dumps({'content': chunk})}\n\n"
                    
                    # 获取使用统计
                    usage = llm_client.get_usage()
                    if usage:
                        yield f"data: {json.dumps({'usage': usage})}\n\n"
                    
                    yield "data: [DONE]\n\n"
                    
                except Exception as e:
                    logger.error(f"LLM调用失败: {str(e)}")
                    yield f"data: {json.dumps({'error': str(e)})}\n\n"

            # 返回流式响应
            response = StreamingHttpResponse(
                stream_response(),
                content_type='text/event-stream'
            )
            response['Cache-Control'] = 'no-cache'
            response['X-Accel-Buffering'] = 'no'
            return response

        except Exception as e:
            logger.error(f"穿搭推荐失败: {str(e)}")
            return Response(
                {"error": f"推荐生成失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def _process_query(self, query: str, username: str) -> str:
        """
        智能处理查询内容，支持多轮对话
        
        Args:
            query: 原始查询
            username: 用户名
            
        Returns:
            处理后的查询内容
        """
        # 如果查询已经包含用户名，直接返回
        if f"为{username}" in query:
            return query
        
        # 如果是简单的对话内容，添加用户上下文
        if not any(keyword in query for keyword in ['推荐', '穿搭', '搭配']):
            return f"为{username}：{query}"
        
        # 如果是推荐请求但没有用户名，添加用户名
        if '推荐' in query and not f"为{username}" in query:
            return f"为{username}推荐{query.replace('推荐', '').strip()}"
        
        return query

    @action(detail=False, methods=["get"])
    def chat_history(self, request):
        """获取用户对话历史"""
        try:
            username = request.GET.get('username', '')
            if not username:
                return Response(
                    {"error": "用户名不能为空"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 从Redis获取历史记录
            redis_conn = get_redis_connection("default")
            history_key = f"user:chat:{username}"
            history = redis_conn.get(history_key)

            if not history:
                return Response([])

            # 解析历史记录
            history_text = history.decode('utf-8')
            # 这里可以添加历史记录的解析逻辑
            # 暂时返回简单的文本格式
            return Response([{
                "role": "system",
                "content": history_text,
                "timestamp": "历史记录"
            }])

        except Exception as e:
            logger.error(f"获取对话历史失败: {str(e)}")
            return Response(
                {"error": f"获取历史记录失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=["post"])
    def clear_history(self, request):
        """清空用户对话历史"""
        try:
            username = request.data.get('username', '')
            if not username:
                return Response(
                    {"error": "用户名不能为空"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 从Redis删除历史记录
            redis_conn = get_redis_connection("default")
            history_key = f"user:chat:{username}"
            redis_conn.delete(history_key)

            return Response({"message": "历史记录已清空"})

        except Exception as e:
            logger.error(f"清空对话历史失败: {str(e)}")
            return Response(
                {"error": f"清空历史记录失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=["post"])
    def create_user(self, request):
        """创建用户资料"""
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(
                    {"message": "用户创建成功", "user": serializer.data},
                    status=status.HTTP_201_CREATED
                )
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
            )
        except Exception as e:
            logger.error(f"创建用户失败: {str(e)}")
            return Response(
                {"error": f"创建用户失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
